package com.winshare.saleAssistant.controller;

import com.alibaba.excel.EasyExcel;
import com.aliyun.oss.OSSException;
import com.winshare.saleAssistant.domain.dto.req.FileDTO;
import com.winshare.saleAssistant.domain.dto.req.StaffExcelExportDTO;
import com.winshare.saleAssistant.domain.dto.req.StaffExcelImportData;
import com.winshare.saleAssistant.domain.dto.resp.StaffExcelExportData;
import com.winshare.saleAssistant.exception.BusinessException;
import com.winshare.saleAssistant.service.FileService;
import com.winshare.saleAssistant.service.StaffService;
import com.winshare.saleAssistant.service.impl.ExcelImportDataListener;
import com.winshare.saleAssistant.util.LogicResponse;
import com.winshare.saleAssistant.util.SecurityManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping(value = "/sys/staff/excel")
@CrossOrigin
@Api(value = "员工管理excel导入、导出功能", description = "员工管理excel导入、导出功能")
public class StaffExcelController {

    private final ExcelImportDataListener excelImportDataListener;

    private final StaffService staffService;

    private final FileService fileService;

    public StaffExcelController(ExcelImportDataListener excelImportDataListener,
                                StaffService staffService, FileService fileService) {
        this.excelImportDataListener = excelImportDataListener;
        this.staffService = staffService;
        this.fileService = fileService;
    }

    @PostMapping("/import")
    @ApiOperation(value = "导入excel文件，需按照样板文件导入",notes = "导入excel文件，需按照样板文件导入")
    public Object upload(@RequestParam(value = "mFile") MultipartFile mFile)  {
        File file = new File(mFile.getOriginalFilename());
        try {
            FileUtils.copyInputStreamToFile(mFile.getInputStream(), file);
            EasyExcel.read(file, StaffExcelImportData.class,excelImportDataListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(file.exists()){
                file.delete();
            }
        }
        return LogicResponse.success("success");
    }

    @PostMapping("/export")
    @ApiOperation(value = "导出职员excel文件,返回一个文件下载链接，自行下载",notes = "导出职员excel文件,返回一个文件下载链接，自行下载")
    public LogicResponse<String> download(@RequestBody @Validated StaffExcelExportDTO staffExcelExportDTO) {

        String fileName = "staff" + System.currentTimeMillis() + ".xlsx";
        List<StaffExcelExportData> staffExcelExportList = staffService.getStaffExcelExportList(staffExcelExportDTO);
        EasyExcel.write(fileName, StaffExcelExportData.class).sheet("staff")
                .doWrite(staffExcelExportList);
        FileDTO fileDTO = new FileDTO();
        try {
            fileDTO.setFileContent(SecurityManager.entryptBase64(Files.readAllBytes(Paths.get(fileName))));
            String randomFileName = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
            fileDTO.setFileName(randomFileName+".xlsx");
            String upload = fileService.upload(fileDTO);
            return LogicResponse.success(Optional.ofNullable(upload).orElse(null));
        } catch (IOException | OSSException e) {
            throw new BusinessException(e.getMessage());
        }finally {
            try {
                Files.deleteIfExists(Paths.get(fileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
